package com.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bhudy.base.BaseServiceImpl;
import com.sys.entity.SysUser;
import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.sys.service.SysUserService;
import com.sys.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;

/**
 * @Author com.bhudy
 * @Description 用户管理Service实现类
 * @Date 2019-10-30 23:09:37
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Serializable> implements SysUserService {

    @Override
    public SysUser login(String json, String loginCode, String password) {
        Subject subject = SecurityUtils.getSubject();//创建subject实例
        if (subject.isAuthenticated() == false) {
            if (json != null) {
                try {
                    Map<String, String> loginMap = JSONObject.parseObject(json, Map.class);
                    if (loginMap != null) {
                        if (loginCode == null || loginCode.equals("")) {
                            loginCode = loginMap.get("loginCode");
                        }
                        if (password == null || password.equals("")) {
                            password = loginMap.get("password");
                        }
                    }
                } catch (Exception e) {
                }
            }

            if (password != null && password.length() > 16) throw new SysException(SysExceptionCode.CODE_40046);

            //将用户名和密码存入UsernamePasswordToken中
            UsernamePasswordToken token = new UsernamePasswordToken(loginCode, password);
            try {
                //将存有用户名和密码的token存进subject中
                subject.login(token);
            } catch (UnknownAccountException e) {
                throw new SysException(SysExceptionCode.CODE_40008);
            } catch (IncorrectCredentialsException e) {
                throw new SysException(SysExceptionCode.CODE_40009);
            } catch (LockedAccountException e) {
                throw new SysException(SysExceptionCode.CODE_40010);
            } catch (AuthenticationException e) {
                throw new SysException(SysExceptionCode.CODE_40010);
            } catch (Exception e) {
                throw new SysException(SysExceptionCode.CODE_40005, e.getMessage());
            }
        }

        return ShiroUtils.getUser();
    }
}
